package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.base.util.JwtUtils;
import com.atguigu.srb.common.exception.Assert;
import com.atguigu.srb.common.exception.BusinessException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.util.MD5;
import com.atguigu.srb.core.mapper.UserAccountMapper;
import com.atguigu.srb.core.mapper.UserLoginRecordMapper;
import com.atguigu.srb.core.pojo.entity.UserAccount;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserLoginRecord;
import com.atguigu.srb.core.pojo.query.UserInfoQuery;
import com.atguigu.srb.core.pojo.vo.LoginVO;
import com.atguigu.srb.core.pojo.vo.RegisterVO;
import com.atguigu.srb.core.pojo.vo.UserInfoVO;
import com.atguigu.srb.core.service.UserInfoService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 用户基本信息 服务实现类
 * </p>
 *
 * @author LiLi
 * @since 2021-09-23
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    UserAccountMapper userAccountMapper;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    UserLoginRecordMapper userLoginRecordMapper;

    @Override
    public void register(RegisterVO registerVO) {
        String mobile = registerVO.getMobile();
        //校验手机号是否已经注册
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("mobile",mobile);
        Integer integer = baseMapper.selectCount(userInfoQueryWrapper);
        if(integer > 0){
            throw new BusinessException(ResponseEnum.MOBILE_EXIST_ERROR);
        }
        //Assert.isTrue(integer>0, ResponseEnum.MOBILE_EXIST_ERROR);
        //插入用户信息记录：user_info
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(registerVO,userInfo);
        userInfo.setNickName(mobile);
        userInfo.setPassword(MD5.encrypt(userInfo.getPassword()));
        baseMapper.insert(userInfo);
        Long userId = userInfo.getId();

        //插入用户账户记录：user_account
        UserAccount userAccount = new UserAccount();
        userAccount.setUserId(userId);
        userAccountMapper.insert(userAccount);
    }

    @Override
    public boolean checkSmsCode(String code,String mobile) {
        boolean b = false;

        String codeCache = (String)redisTemplate.opsForValue().get("srb:sms:code:"+mobile);

        if(!StringUtils.isEmpty(codeCache)&&codeCache.equals(code)){
            b=true;
        }
        return b;
    }

    @Override
    public UserInfoVO login(LoginVO loginVO, String ip) {
        String mobile = loginVO.getMobile();
        String password =loginVO.getPassword();
//        String pass = MD5.encrypt(password);
        Integer userType = loginVO.getUserType();

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("mobile",mobile);
        userInfoQueryWrapper.eq("user_type",userType);
        UserInfo userInfo = baseMapper.selectOne(userInfoQueryWrapper);

        //校验用户信息，生成token
        if(null!=userInfo){
            String passwordDb = userInfo.getPassword();
            //校验失败
            Assert.isTrue(passwordDb.endsWith(MD5.encrypt(password)),ResponseEnum.LOGIN_PASSWORD_ERROR);
            //校验成功
            //根据登录用户的ip生成登录日志
            UserLoginRecord userLoginRecord = new UserLoginRecord();
            userLoginRecord.setUserId(userInfo.getId());
            userLoginRecord.setIp(ip);
            userLoginRecordMapper.insert(userLoginRecord);

        }else {
            //没有用户
            Assert.isTrue(false,ResponseEnum.LOGIN_MOBILE_ERROR);
        }

        UserInfoVO userInfoVO = new UserInfoVO();
        userInfoVO.setHeadImg(userInfo.getHeadImg());
        userInfoVO.setMobile(userInfo.getMobile());
        userInfoVO.setNickName(userInfo.getNickName());
        userInfoVO.setName(userInfo.getName());
        userInfoVO.setUserType(userType);
        //生成token
        userInfoVO.setToken(JwtUtils.createToken(userInfo.getId(),userInfo.getName()));
        return userInfoVO;
    }

    @Override
    public Page<UserInfo> listPage(Page<UserInfo> pageModel, UserInfoQuery userInfoQuery) {
        String mobile = userInfoQuery.getMobile();
        Integer status = userInfoQuery.getStatus();
        Integer userType = userInfoQuery.getUserType();

        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper
                .eq(!StringUtils.isEmpty(mobile),"mobile",mobile)
                .eq(null!=status,"status",status)
                .eq(null!=userType,"user_type",userType);
        Page<UserInfo> userInfoPage = baseMapper.selectPage(pageModel, userInfoQueryWrapper);
        return userInfoPage;
    }

    @Override
    public void lock(Long id, Integer status) {
        UserInfo userInfo = new UserInfo();
        userInfo.setId(id);
        userInfo.setStatus(status);
        baseMapper.updateById(userInfo);
    }

    @Override
    public boolean checkMobile(String mobile) {
        boolean b = false;
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        userInfoQueryWrapper.eq("mobile",mobile);
        Integer integer = baseMapper.selectCount(userInfoQueryWrapper);

        if (integer>0){
            b=true;
        }

        return b;

    }

    @Override
    public UserInfo getUserInfoById(Long userId) {
        UserInfo userInfo = baseMapper.selectById(userId);

        return userInfo;
    }
}
